package lucene.server.web.controller.client;


import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import lucene.server.common.model.Result;
import lucene.server.common.model.SearchPage;
import lucene.server.common.utils.JsonUtil;
import lucene.server.core.LuceneIndex;
import lucene.server.core.LuceneService;
import lucene.server.core.query.QueryBuilder;
import lucene.server.common.enums.QueryEnum;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Sort;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/client")
public class ClientController {
    @PostMapping(value = "/wrapper")
    public Result<?> wrapper(@RequestBody String body) throws Exception {

        ObjectNode jsonObject = JsonUtil.getJsonObject(body);
        if (!jsonObject.has("name") ){
            return Result.error("索引不存在,请检查From参数name值");
        }

        LuceneIndex luceneIndex =  LuceneService.getIndex(jsonObject.get("name").asText());

        if (luceneIndex ==null ){
            return Result.error("索引不存在,请检查From参数name值");
        }

        Object result = null;
        QueryBuilder queryBuilder = new QueryBuilder(jsonObject, luceneIndex.getIndexConfig().getFieldsConfig());
        if (queryBuilder.getType() == QueryEnum.SELECT){
            SearchPage searchPage = new SearchPage(queryBuilder.getPage(),queryBuilder.getPageSize());
            searchPage.setQueryString(queryBuilder.build().toString());
            searchPage = luceneIndex.getSearchService().searchList(queryBuilder.build(),searchPage,queryBuilder.getSort(),queryBuilder.getField());
            return Result.OK(searchPage);
        }else if (queryBuilder.getType() == QueryEnum.DELETE){
            result = luceneIndex.getDeleteService().deleteDocuments(queryBuilder.build());
        }else if (queryBuilder.getType() == QueryEnum.INSERT){
            result = luceneIndex.getInsertService().addDocument(queryBuilder.buildDocument());
        }else if (queryBuilder.getType() == QueryEnum.UPDATE){
            result = luceneIndex.getUpdateService().updateDocumentFieldsValue(queryBuilder.buildDocument(),queryBuilder.buildFieldQuery(luceneIndex.getIndexConfig().getKey()));
        }else if (queryBuilder.getType() == QueryEnum.GROUP){
            return Result.OK(luceneIndex.getGroupService().groupSearch(queryBuilder.build(),queryBuilder.getField(),"totalHits",queryBuilder.getField()));
        }else if (queryBuilder.getType() == QueryEnum.COUNT){
            return Result.OK(luceneIndex.getSearchService().count(queryBuilder.build()));
        }
        return Result.OK(result);
    }

}
